package com.thunbu.lib_common.base

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewStub
import android.widget.RelativeLayout
import androidx.annotation.CallSuper
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import com.thunbu.lib_common.R
import com.thunbu.lib_common.utils.DynamicPermissionHelper
import com.thunbu.lib_common.utils.ScreenUtils
import pub.devrel.easypermissions.EasyPermissions
import java.lang.reflect.ParameterizedType

abstract class BaseFragment<VDB:ViewDataBinding> : Fragment(), EasyPermissions.RationaleCallbacks {

    lateinit var rootView: View

    lateinit var bindViews: VDB

    lateinit var status:View
    lateinit var toolBar: ViewStub
    lateinit var content: ViewStub

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        rootView = inflater.inflate(R.layout.base_layout_plus, container, false)
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initStatus()
        initContent()

        onCreated()
    }


    /**
     * 所有初始化工作完成后调用该方法
     */
    abstract fun onCreated()


    /**
     * 再次改变状态栏
     */
    private fun initStatus() {
        val decor = activity?.window?.decorView
        //如果没有开启全面屏
        if ((activity as BaseActivity<*>).isFullScreen()) {
            //显示自定义status
            val lp = status.layoutParams
            lp.height = ScreenUtils.getStatusBarHeight(requireActivity())
            status.layoutParams = lp
            //设置颜色
            status.setBackgroundColor(setStatusColor())
        }else{
            //设置状态栏的背景颜色
            //activity?.window?.statusBarColor = setStatusColor()
        }
    }


    @CallSuper
    override fun onResume() {
        super.onResume()
        setStatusTheme()
    }


    private fun setStatusTheme() {
        val decor = activity?.window?.decorView
        //是否显示深色Status
        if (isDarkStatus()) {
            decor?.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        } else {
            decor?.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        }
    }


    /**
     * 设置ToolBar布局
     *
     * @param isFloat 是否使得ToolBar悬浮
     * @注意 : toolbar必须要给个Id
     */
    open fun <T : ToolBarHolder> setToolBar(clazz: Class<T>, isFloat: Boolean = false): T {
        val toolBarHolder = clazz.newInstance()
        toolBar.layoutResource = toolBarHolder.provideLayoutId()
        val tooBarView = toolBar.inflate()
        tooBarView.visibility = View.VISIBLE
        toolBarHolder.setContentView(tooBarView!!)
        //如果没有开启悬浮
        if (!isFloat) {
            if (tooBarView.id < 0) {
                tooBarView.id = android.R.id.title
            }
            val contentLp = bindViews.root.layoutParams as RelativeLayout.LayoutParams
            contentLp.addRule(RelativeLayout.BELOW, tooBarView.id)
            bindViews.root.layoutParams = contentLp
        }else{
            tooBarView.bringToFront()
        }
        //如果开启全面屏，适配status
        if ((activity as BaseActivity<*>).isFullScreen()) {
            val lp = (tooBarView.layoutParams as RelativeLayout.LayoutParams)
            lp.topMargin = ScreenUtils.getStatusBarHeight(requireActivity())
            tooBarView.layoutParams = lp
        }
        return toolBarHolder as T
    }


    /**
     * 初始化内容
     */
    private fun initContent() {
        val bindClassName = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0].toString().split(" ")[1]
        bindViews = Class.forName(bindClassName).getMethod("inflate", LayoutInflater::class.java).invoke(null,layoutInflater) as VDB
        bindViews.lifecycleOwner = this
        replaceViewStub(content,bindViews.root)
    }


    /**
     *  <替换 View>
     *  <使 DataBinding 替换 ViewStub 的方案>
     */
    private fun replaceViewStub(viewStub: View,replaceView:View){
        val lp = viewStub.layoutParams
        replaceView.layoutParams = lp
        with(viewStub.parent as ViewGroup){
            removeView(viewStub)
            addView(replaceView)
        }
    }


    /**
     * 动态设置状态栏颜色
     */
    fun setStatusColor(color:Int){
        //如果没有开启全面屏
        if ((activity as BaseActivity<*>).isFullScreen()) {
            //设置颜色
            status.setBackgroundColor(color)
        }else{
            //设置状态栏的背景颜色
            activity?.window?.statusBarColor = color
        }
    }


    /**
     * 设置状态栏颜色，默认为透明色（如果开启全面屏，会使用自定义status，如果出现嵌套Fragment的情况，会出现尴尬的场景）
     */
    open fun setStatusColor(): Int = Color.TRANSPARENT


    /**
     * 设置状态栏字体颜色是否为深色，默认浅色
     */
    open fun isDarkStatus(): Boolean {
        val activity = requireActivity()
        if (activity is BaseActivity<*>){
            return activity.isDarkStatus()
        }else{
            return false
        }
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        DynamicPermissionHelper.getInstance()
                .onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        DynamicPermissionHelper.getInstance().onRationaleAccepted(requestCode)
    }

    override fun onRationaleDenied(requestCode: Int) {
        DynamicPermissionHelper.getInstance().onRationaleDenied(requestCode)
    }
}